package logic

import (
	"context"
	"house/pkg"
	"net/http"
	"path/filepath"

	"api/internal/svc"
	"api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UploadLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUploadLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UploadLogic {
	return &UploadLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UploadLogic) Upload(req *http.Request) (resp *types.Response, err error) {
	// todo: 文件上传
	file, m, err := req.FormFile("image")
	if err != nil {
		return &types.Response{
			Code: 500,
			Msg:  err.Error(),
			Data: nil,
		}, nil
	}
	ext := filepath.Ext(m.Filename)
	if ext != ".jpg" && ext != ".png" {
		return &types.Response{
			Code: 500,
			Msg:  "文件类型仅支持“jpg”或是“png”类型",
			Data: nil,
		}, nil
	}
	if m.Size >= 1*1024*1024 {
		return &types.Response{
			Code: 500,
			Msg:  "图片限制在200kb以下",
			Data: nil,
		}, nil
	}
	yun, _ := pkg.QiNiuYun(file, m.Filename)
	return &types.Response{
		Code: 200,
		Msg:  "文件上传成功",
		Data: yun,
	}, nil
}
